package com.xiaoqiudong.forum.controller;

import com.xiaoqiudong.forum.common.AppResult;
import com.xiaoqiudong.forum.common.ResultCode;
import com.xiaoqiudong.forum.common.utils.MD5Util;
import com.xiaoqiudong.forum.common.utils.StringUtils;
import com.xiaoqiudong.forum.common.utils.UUIDUtils;
import com.xiaoqiudong.forum.config.AppConfig;
import com.xiaoqiudong.forum.exception.ApplicationException;
import com.xiaoqiudong.forum.model.User;
import com.xiaoqiudong.forum.service.IUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Nonnull;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import jakarta.validation.constraints.NotNull;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.web.bind.annotation.*;

/**
 * Created with IntelliJ IDEA
 * Descroption
 * User:dell
 * Date:2025-08-23
 * Time:14:23
 */
@Slf4j
@RestController
@Tag(name = "用户相关的接口")
@RequestMapping("/user")
public class UserController {

    /**
     * 用户注册
     * @param username 用户名
     * @param nickname 用户昵称
     * @param password 密码
     * @param passwordRepeat 重复密码
     */
    @Resource
    private IUserService userService;
    @Operation(description = "注册接口")
    @PostMapping("/register")
    public AppResult register(@Parameter(name = "username",description = "用户名") @RequestParam("username") @NotNull String username,
                              @Parameter(name = "nickname",description = "昵称") @RequestParam("nickname") @NotNull String nickname,
                              @Parameter(name = "password",description = "密码") @RequestParam("password") @NotNull String password,
                              @Parameter(name = "passwordRepeat",description = "确认密码") @RequestParam("passwordRepeat") @NotNull String passwordRepeat){
//        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(nickname)
//        || StringUtils.isEmpty(password) || StringUtils.isEmpty(passwordRepeat)){
//            log.info(ResultCode.FAILED_PARAMS_VALIDATE.toString());
//            return AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE);
//        }
        User user = new User();
        user.setUsername(username);
        user.setNickname(nickname);
        //处理密码
        if (!password.equals(passwordRepeat)){
            log.info(ResultCode.FAILED_TWO_PWD_NOT_SAME.toString());
            return AppResult.fail(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        //加密密码
        String salt = UUIDUtils.UUID_32();
        String encryptPassword = MD5Util.md5Salt(password,salt);
        user.setSalt(salt);
        user.setPassword(encryptPassword);
        //调用service
        userService.createNormalUser(user);
        return AppResult.success();
    }

    /**
     * 用户登录
     * @param request
     * @param username 用户名
     * @param password 密码
     * @return
     */
    @Operation(description = "登录接口")
    @PostMapping("/login")
    public AppResult login(HttpServletRequest request,
                           @Parameter(name = "username",description = "用户名") @RequestParam("username") @Nonnull String username,
                           @Parameter(name = "password",description = "密码") @RequestParam("password") @Nonnull String password){
        User user = userService.login(username,password);
        if (user == null){
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            return AppResult.fail(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        HttpSession session = request.getSession(true);
        //创建会话
        session.setAttribute(AppConfig.USER_SESSION,user);
        return AppResult.success();
    }


   @Operation(description = "获取用户信息")
   @GetMapping("/info")
   public AppResult<User> getUserInfo(HttpServletRequest request,
                                      @Parameter(name = "id",description = "用户id") @RequestParam(value = "id",required = false) Long id){
        User user = null;
        if (id == null){
            HttpSession session = request.getSession(false);
//            if (session == null || session.getAttribute(AppConfig.USER_SESSION)== null){
//                return AppResult.fail(ResultCode.FAILED_FORBIDDEN);
//            }
            user = (User) session.getAttribute(AppConfig.USER_SESSION);

        }else {
            user = userService.selectById(id);
        }
        if (user == null){
            return AppResult.fail(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        return AppResult.success(user);
   }


    @Operation(description = "用户退出")
    @GetMapping("/logout")
    public AppResult logout(HttpServletRequest request){
        HttpSession session = request.getSession(false);
        if (session != null){
            //注销session
            session.invalidate();
        }
        return AppResult.success();

    }

    @Operation(description = "用户信息修改")
    @PostMapping("modifyInfo")
    public AppResult modifyInfo(HttpServletRequest request,
                                @Parameter(name = "username" ,description = "用户名") @RequestParam(value = "username",required = false) String username,
                                @Parameter(name = "nickname" ,description = "昵称") @RequestParam(value = "nickname",required = false) String nickname,
                                @Parameter(name = "gender" ,description = "性别") @RequestParam(value = "gender",required = false) Byte gender,
                                @Parameter(name = "email" ,description = "邮箱") @RequestParam(value = "email",required = false) String email,
                                @Parameter(name = "phoneNum" ,description = "电话") @RequestParam(value = "phoneNum",required = false) String phoneNum,
                                @Parameter(name = "remark" ,description = "个人简介") @RequestParam(value = "remark",required = false) String remark){

        //非空校验，都为空，没有修改
        if (StringUtils.isEmpty(username) && StringUtils.isEmpty(nickname)
                && gender == null  && StringUtils.isEmpty(email)
                && StringUtils.isEmpty(phoneNum) && StringUtils.isEmpty(remark)){
            log.warn("没有实质修改");
            return AppResult.fail("请输入要修改的值");
        }
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //封装用户
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setUsername(username);
        updateUser.setNickname(nickname);
        updateUser.setGender(gender);
        updateUser.setEmail(email);
        updateUser.setPhoneNum(phoneNum);
        updateUser.setRemark(remark);

        //调用service
        userService.modifyInfo(updateUser);
        //查询最新消息
        user = userService.selectById(user.getId());
        //返回最新消息
        session.setAttribute(AppConfig.USER_SESSION,user);
        return AppResult.success(user);

    }

    @Operation(description = "修改密码")
    @PostMapping("/modifyPwd")
    public AppResult modifyPassword(HttpServletRequest request,
                                    @Parameter(name = "oldPassword" ,description = "旧密码") @RequestParam("oldPassword") @Nonnull String oldPassword,
                                    @Parameter(name = "newPassword" ,description = "新密码") @RequestParam("newPassword") @Nonnull String newPassword,
                                    @Parameter(name = "passwordRepeat" ,description = "确认密码") @RequestParam("passwordRepeat") @Nonnull String passwordRepeat){

        //验证新密码和确认密码相同
        if (!newPassword.equals(passwordRepeat)){
            log.warn(ResultCode.FAILED_TWO_PWD_NOT_SAME.toString());
            return AppResult.fail(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        //获取登陆行信息
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        //调用service更改密码
        userService.modifyPassword(user.getId(),oldPassword,newPassword);
        //销毁session 重新登录
        if(session != null){
            session.invalidate();
        }
        return AppResult.success();
    }
}
